<script setup>
import {getCertificatesTypeAPI, getAddressListAPI,addPatientAPI,getPatientDetailAPI,editPatientAPI   } from '@/api/user'
import { onMounted, ref } from 'vue'
import { useRouter , useRoute} from 'vue-router'
import { ElMessage } from 'element-plus'

// 全局路由对象
const router = useRouter()

// 页面路有对象
const route = useRoute()

// 页面标题
const title = ref('')

// 表单数据
const formData = ref({
    name: '',// 姓名
   sex: 0,// 性别
   certificatesType: "",
   certificatesNo: "",
   birthdate: '',
   phone: '', // 手机号
   isMarry: 0, // 是否已婚
   isInsure: 0,
   addressSelected: [],
   address: '',
   contactsName: '',
   contactsCertificatesType: '',
   contactsCertificatesNo: '',
   contactsPhone: '',
})

// 校验规则
const rules = {
    name: [
        { required: true, message: '请输入用户姓名', trigger: 'blur' },
        { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
    ],// 姓名
   sex: [
      { required: true, message: '请选择性别', trigger: 'change' },
   ],// 性别
   certificatesType: [
      { required: true, message: '请选择证件类型', trigger: 'change' },
   ],
   certificatesNo: [
      { required: true, message: '请输入证件号码', trigger: 'blur' },
   ],
   birthdate: [
      { required: true, message: '请选择出生日期', trigger: 'change' },
   ],
   phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
   ], // 手机号
   isMarry: [
      { required: true, message: '请选择婚姻状况', trigger: 'change' },
   ], // 是否已婚
   isInsure: [
      { required: true, message: '请选择自费/医保', trigger: 'change' },
   ],
   addressSelected: [
      { required: true, message: '请选择地址', trigger: 'change' },
   ],
   address: [
      { required: true, message: '请输入详细地址', trigger: 'blur' },
   ],
}

// 表单对象
const formRef = ref(null)

// 证件类型
const certificatesTypeOptions = ref([])

// 获取证件类型
const getCertificatesType = async () => {
    const res = await getCertificatesTypeAPI()
    // console.log(res)
    certificatesTypeOptions.value = res.data
}

// 判断当前页面是添加还是编辑
const renderPage = async () => {
   console.log(route.query);
    if(route.query.id) {
        // 编辑
        title.value = '编辑就诊人'
        // 获取就诊人数据详情
        const res =  await getPatientDetailAPI(route.query.id)
        // console.log(route.query.id);
        console.log(res);
        formData.value = res.data

        // 处理地址
        formData.value.addressSelected = [res.data.provinceCode, res.data.cityCode, res.data.districtCode]
    } else {
        // 添加
        title.value = '添加就诊人'
    }
}
// 动态加载数据
const props  = {
  lazy: true,
  async lazyLoad(node, resolve) {
    
    const parentId = node.data.parentId || 86
    // console.log(node);
   const res = await getAddressListAPI(parentId)
   const showArr = res.data.map(item => {
    return {
        parentId: item.id,
        label: item.name,
        value: item.value,
        leaf: item.hasChildren ? false : true
    }
   })
   resolve(showArr)

  },
}

// 取消
const cancel = () => {
    router.push(route.query.fullPath )
}
onMounted(() => {
    renderPage ()
    getCertificatesType()
})

// 添加急诊人
const addPatient = () => {
    formRef.value.validate(async (valid) => {
       if(valid) {
          // 发送请求
        //  判断当前状态
          if(route.query.id) {
                // 编辑
                const res = await editPatientAPI(formData.value)
                console.log(res);
                if (res.code === 200) {
                    ElMessage.success('编辑就诊人成功')
                    router.push(route.query.fullPath )
                } else {
                    ElMessage.error('编辑就诊人失败')
                }
          } else {
            // 添加
            const res =  await addPatientAPI(formData.value)
            //   console.log(res);
            if (res.code === 200) {
                ElMessage.success('添加就诊人成功')
                router.push(route.query.fullPath )
            } else {
                ElMessage.error('添加就诊人失败')
            }
          }
       }
    })
}



</script>

<template>
    <div>
        <el-card >
            <template #header>
                <span class="header">{{ title }}</span>
            </template>
            <el-form ref="formRef" :model="formData" label-width="100px" :rules="rules">
                <el-divider content-position="left">就诊人信息</el-divider>
                <el-form-item label="用户姓名" prop="name">
                    <el-input v-model="formData.name"  placeholder="请输入用户姓名"></el-input>
                </el-form-item>
                <el-form-item label="证件类型" prop="certificatesType">
                    <el-select v-model="formData.certificatesType"  placeholder="请选择证件类型">
                        <el-option v-for="item in certificatesTypeOptions" :key="item.id" :value="item.value" :label="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号码" prop="certificatesNo">
                    <el-input v-model="formData.certificatesNo" placeholder="请输入证件号码"></el-input>
                </el-form-item>
                <el-form-item label="用户性别" prop="sex">
                    <el-radio-group v-model="formData.sex" class="ml-4" >
                        <el-radio :value="0" size="large" :label="0">女</el-radio>
                        <el-radio :value="1" size="large" :label="1">男</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="出生日期" prop="birthdate">
                    <el-date-picker
                        value-format="YYYY-MM-DD"
                        v-model="formData.birthdate"
                        type="date"
                        placeholder="请选择出生日期"
                    />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入手机号码"></el-input>
                </el-form-item>
                
                <el-divider content-position="left">建档信息（完善后部分医院首次就诊不排队建档）</el-divider>
                
                <el-form-item label="婚姻状况" prop="isMarry">
                    <el-radio-group  v-model="formData.isMarry" class="ml-4">
                        <el-radio :value="0" size="large" :label="0">已婚</el-radio>
                        <el-radio :value="1" size="large" :label="1">未婚</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="自费/医保" prop="isInsure">
                    <el-radio-group v-model="formData.isInsure" class="ml-4">
                        <el-radio :value="0" size="large" :label="0">医保</el-radio>
                        <el-radio :value="1" size="large" :label="1">自费</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="当前住址" prop="address">
                    <el-cascader v-model="formData.addressSelected" :props="props" />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="formData.address" placeholder="请输入详细地址"></el-input>
                </el-form-item>
                
                <el-divider content-position="left">联系人信息（选填）</el-divider>
                
                <el-form-item label="用户姓名">
                    <el-input v-model="formData.contactsName" placeholder="请输入用户姓名"></el-input>
                </el-form-item>
                <el-form-item label="证件类型">
                    <el-select v-model="formData.contactsCertificatesType" placeholder="请选择证件类型">
                        <el-option v-for="item in certificatesTypeOptions" :key="item.id" :value="item.value" :label="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="证件号码">
                    <el-input v-model="formData.contactsCertificatesNo" placeholder="请输入证件号码"></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                    <el-input v-model="formData.contactsPhone" placeholder="请输入手机号码"></el-input>
                </el-form-item>
            </el-form>
            <el-row style="width: 100%; justify-content: center;">
                <el-button type="info" size="large" @click="cancel">取消</el-button>
                <el-button type="primary" size="large" @click="addPatient">提交</el-button>
            </el-row>
        </el-card>
    </div>
</template>


<style lang="scss" scoped>
.el-card {
    width: 1000px;
    .header {
        font-size: 24px;
        font-weight: 700;
        color: #666;
    }
    .el-form {
        width: 100%;
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        align-items: center;
        .el-form-item {
            width: 70%;
            
        }
    }
}
</style>